using Microsoft.OpenApi.Models;
using StudentVideo.Shared.Models;
using Swashbuckle.AspNetCore.SwaggerGen;

namespace StudentVideo.Filters;

public class HttpResultOperationFilter: IOperationFilter {
   public void Apply(OpenApiOperation operation, OperationFilterContext context) {
      // 获取方法的实际返回类型
      var returnType = context.MethodInfo.ReturnType;

      // 处理返回类型为Task<T>的异步方法
      if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task<>)) {
         returnType = returnType.GetGenericArguments()[0];
      }

      if(returnType == typeof(void)) {
         return;
      }

      // 动态构建 HttpResult<T> 类型
      var httpResultType = typeof(HttpResult<>).MakeGenericType(returnType);

      // 为 HttpResult<T> 生成 Schema
      var schema = context.SchemaGenerator.GenerateSchema(httpResultType, context.SchemaRepository);

      // 更新Swagger文档中的响应
      foreach (var response in operation.Responses) {
         foreach (var content in response.Value.Content.Values) {
            content.Schema = schema;
         }
      }
   }
}
